import 'package:flutter/material.dart';
import 'package:zhuanzu/page/base_page.dart';
import 'package:zhuanzu/page/v2ex_detail_page.dart';
import 'package:zhuanzu/utils/api.dart';

class ExplorePage extends StatefulWidget {
  const ExplorePage({Key? key}) : super(key: key);

  @override
  State<ExplorePage> createState() => _ExplorePageState();
}

class _ExplorePageState extends State<ExplorePage> {
  List<dynamic> _posts = [];
  bool _isLoading = true; // 首次加载状态
  bool _isFetchingMore = false; // 是否正在加载更多
  bool _hasMore = true; // 是否还有更多数据
  int _page = 1;
  final int _pageSize = 20;

  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _fetchPosts();

    _scrollController.addListener(() {
      if (_scrollController.position.pixels >=
              _scrollController.position.maxScrollExtent - 100 &&
          !_isFetchingMore &&
          _hasMore &&
          !_isLoading) {
        _fetchMorePosts();
      }
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  Future<void> _fetchPosts() async {
    setState(() {
      _isLoading = true;
      _page = 1;
      _hasMore = true;
      _posts.clear();
    });

    try {
      final res = await Api.get(
        '/cms/post/page',
        params: {
          'page': _page.toString(),
          'size': _pageSize.toString(),
          'type': 'v2ex',
        },
      );

      if (res['code'] == 0) {
        final data = res['data'] as Map<String, dynamic>;
        final records = data['records'] as List<dynamic>;

        setState(() {
          _posts = records;
          _hasMore = records.length == _pageSize;
          if (_hasMore) _page++;
        });
      } else {
        print("接口返回失败: ${res['msg']}");
      }
    } catch (e) {
      print("加载失败: $e");
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _fetchMorePosts() async {
    if (!_hasMore) return;

    setState(() {
      _isFetchingMore = true;
    });

    try {
      final res = await Api.get(
        '/cms/post/page',
        params: {
          'current': _page.toString(),
          'size': _pageSize.toString(),
          'type': 'v2ex',
        },
      );

      if (res['code'] == 0) {
        final data = res['data'] as Map<String, dynamic>;
        final records = data['records'] as List<dynamic>;
        final total = data['total'] as int? ?? 0;
        final currentPage = data['current'] as int? ?? 1;
        final pageSize = data['size'] as int? ?? 20;

        setState(() {
          _posts.addAll(records);
          _hasMore = currentPage * pageSize < total;
          if (_hasMore) _page++;
        });
      } else {
        print("接口返回失败: ${res['msg']}");
      }
    } catch (e) {
      print("加载更多失败: $e");
    } finally {
      setState(() {
        _isFetchingMore = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return BasePage(
      child: Scaffold(
        backgroundColor: const Color(0xFFFFFFFF), // 纯白色
        appBar: AppBar(title: const Text("热帖")),
        body: _isLoading
            ? const Center(child: CircularProgressIndicator())
            : ListView.separated(
                controller: _scrollController,
                itemCount: _posts.length + 1, // 多一个底部加载或无更多提示
                separatorBuilder: (_, __) => const Divider(height: 1),
                itemBuilder: (context, index) {
                  if (index == _posts.length) {
                    // 底部显示加载中或者无更多
                    if (_hasMore) {
                      return const Padding(
                        padding: EdgeInsets.symmetric(vertical: 16),
                        child: Center(child: CircularProgressIndicator()),
                      );
                    } else {
                      return const Padding(
                        padding: EdgeInsets.symmetric(vertical: 16),
                        child: Center(child: Text("没有更多了")),
                      );
                    }
                  }
                  final post = _posts[index];
                  return ListTile(
                    leading: const Icon(Icons.whatshot, color: Colors.orange),
                    title: Text(post['title']),
                    subtitle: Text(post['content'] ?? ''),
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (_) => V2exDetailPage(
                            postId: post['id'],
                            title: post['title'],
                          ),
                        ),
                      );
                    },
                  );
                },
              ),
      ),
    );
  }
}
